/*
 * @Description: 排序设置上下文
 * @Author: Rfan
 * @Date: 2022-01-08 16:30:05
 * @LastEditTime: 2023-01-12 16:29:41
 */

import { createContext, useContext, useEffect, useReducer } from 'react';
import { Modal, message } from 'antd';
import { SortReducer } from '../reducers/SortReducer';
import {
  ADD_SORTING,
  DELETE_SORTING,
  EDIT_SORTING,
  INIT_QUERY,
  INIT_TABLE,
  SET_QUERY,
  SET_SELECTED_ITEM,
  SET_SELECT_AT,
  SET_SELECT_FOND,
  SET_SELECT_LEVEL,
  SET_SORTING_LIST
} from '../constants';
import {
  addSorting,
  deleteSorting,
  editSorting,
  fetchSortingList
} from '@/api/rulesettings/ruleSetting';

const initialState = {
  // 当前选中的项目
  selectUnit: {},
  selectFond: {},
  selectAT: {},
  selectLevel: {},
  // 选中的表格条目
  selectItems: [],

  // 列表相关
  listQuery: {},
  list: [],
  loading: false,

  dialog: {
    fieldList: []
  },

  sortType: [
    { id: 0, name: '正序', color: 'blue' },
    { id: 1, name: '倒序', color: 'green' }
  ]
};

const SortContext = createContext();

const SortContextProvider = (props) => {
  const [state, dispatch] = useReducer(SortReducer, initialState);

  const actions = {
    /**
     * @description: 设置选中的全宗
     * @param {*} data 全宗
     */
    setSelectFond(data) {
      dispatch({ type: SET_SELECT_FOND, data });
    },

    /**
     * @description: 设置选中的档案类型
     * @param {*} data 档案类型
     */
    setSelectAT(data) {
      dispatch({ type: SET_SELECT_AT, data });
    },

    /**
     * @description: 设置选中的层级
     */
    /**
     * @description: 设置选中的层级
     * @param {*} data 选中的层级
     */
    setSelectLevel(data) {
      dispatch({ type: SET_SELECT_LEVEL, data });
    },

    /**
     * @description: 切换层级时将页码信息，选中信息等进行初始化设置。listQuery由setListQuery管理
     */
    initTable() {
      dispatch({ type: INIT_TABLE });
    },

    /**
     * @description: 初始化排序列表请求条件
     * @param {object} data 修改的请求内容
     */
    initListQuery(data) {
      dispatch({ type: INIT_QUERY, data });
    },

    /**
     * @description: 设置排序列表请求条件
     * @param {{key: string, value: any}[]} info 修改的请求内容
     */
    setListQuery(info) {
      dispatch({ type: SET_QUERY, info });
    },

    /**
     * @description: 获取排序列表
     * @param {*} listQuery 请求参数
     */
    getSortingList(listQuery) {
      fetchSortingList(listQuery).then((res) => {
        const { data } = res;
        dispatch({ type: SET_SORTING_LIST, data });
      });
    },

    /**
     * @description: 直接设置列表
     * @param {object[]} data 设置的列表
     */
    setList(data) {
      dispatch({ type: SET_SORTING_LIST, data });
    },

    /**
     * @description: 设置表格中选中条目的key
     * @param {*} selectArr
     */
    setSelectKey(selectArr) {
      dispatch({ type: SET_SELECTED_ITEM, data: selectArr });
    },

    /**
     * @description: 增加排序字段
     * @param {*} query 请求参数
     */
    addSortingFunc(query) {
      return new Promise((resolve, reject) => {
        addSorting(query)
          .then((res) => {
            message.success('新建成功');
            const { data } = res;
            dispatch({ type: ADD_SORTING, data });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },

    /**
     * @description: 编辑排序字段
     * @param {*} query 请求参数
     */
    editSortingFunc(query) {
      return new Promise((resolve, reject) => {
        editSorting(query)
          .then((res) => {
            message.success('保存成功');
            const { data } = res;
            dispatch({ type: EDIT_SORTING, data, id: data?.rule?.id });
            resolve(data);
          })
          .catch((err) => reject(err));
      });
    },

    /**
     * @description: 保存字段排序方法
     * @param {*} queryList 请求参数列表
     * @param {*} field 选中的元数据
     * @return {*}
     */
    updateSortFunc(queryList, field) {
      const promiseList = queryList.map((query) => editSorting(query));
      return new Promise((resolve, reject) => {
        Promise.all(promiseList)
          .then((resList) => {
            message.success('保存成功');
            resList.forEach((res) => {
              const { data } = res;
              dispatch({ type: EDIT_SORTING, data, id: data?.rule?.id });
            });
            resolve(resList);
          })
          .catch((err) => reject(err));
      });
    },

    /**
     * @description: 根据id、ids删除排序字段
     * @param {number|number[]} id 删除字段的id
     * @param {string} confirmContent 确认弹窗内容
     */
    deleteSortingFunc(id, confirmContent = '确认删除选中的排序？') {
      Modal.confirm({
        title: '删除',
        content: confirmContent,
        onOk() {
          const ids = id instanceof Array ? id.join(',') : id;
          deleteSorting(ids).then((res) => {
            message.success('删除成功');
            const data = res.data.map((id) => parseInt(id, 10));
            dispatch({ type: DELETE_SORTING, ids: data });
          });
        },
        onCancel() {}
      });
    }
  };

  // watch listQuery来加载排序列表
  useEffect(() => {
    if (state.listQuery && JSON.stringify(state.listQuery) !== '{}') {
      actions.getSortingList(state.listQuery);
    }
  }, [state.listQuery]);

  return (
    <SortContext.Provider value={{ ...state, ...actions }}>{props.children}</SortContext.Provider>
  );
};

export const useSortContext = () => {
  return useContext(SortContext);
};

export { SortContext, SortContextProvider };
